package 链表.双指针;


import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * https://leetcode.cn/problems/merge-k-sorted-lists/?favorite=2cktkvj
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493139&idx=1&sn=f6ffe30bc9cb99a324d34ddf3e8ca55f&chksm=9bd4181baca3910d98ef63759229e65442c66bb5f19f6f5b6baf29195d213f5c7f7d964fcac1&scene=178&cur_album_id=2165022824317485057#rd
 */
public class _23_合并K个升序链表 {

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;

        ListNode sentinal = new ListNode(-1);
        ListNode node = sentinal;

        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });

        for (int i = 0; i < lists.length; i++) {
            if (lists[i] != null) {
                queue.offer(lists[i]);
            }
        }

        while (!queue.isEmpty()) {
            ListNode listNode = queue.poll();
            node.next = listNode;
            listNode = listNode.next;

            if (listNode != null) {
                queue.offer(listNode);
            }

            node = node.next;
        }
        return sentinal.next;
    }

}
